package com.yylending.las.lending.quota.face;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.livedetect.LiveDetectActivity;
import com.tbruyelle.rxpermissions.Permission;
import com.yyfax.common.CLog;
import com.yyfax.common.tools.DensityUtil;
import com.yyfax.infrastructure.PermissionsGrantedHelper;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.Constants;
import com.yylending.las.Global;
import com.yylending.las.R;
import com.yylending.las.StatIDSet;
import com.yylending.las.base.BaseFragment;
import com.yylending.las.common.widgets.CommonDialog;
import com.yylending.las.lending.quota.ApplyQuotaActivity;
import com.yylending.las.lending.quota.baseinfo.CustomerInfoModel;
import com.yylending.las.lending.quota.baseinfo.CustomerInfoPresenter;
import com.yylending.las.lending.quota.entity.CustomerBean;
import org.apaches.commons.codec.binary.Base64;

import java.util.HashMap;

import static android.app.Activity.RESULT_OK;

/**
 * Created by laixj on 2017/2/8.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class FaceQuotaFragment extends BaseFragment implements FacePresenter.View, CustomerInfoPresenter.View {
	private final static String TAG = "FaceQuotaFragment";

	//0待刷脸、1刷脸失败、2待验证、3刷脸成功
	private final static int STATUS_WAIT = 0;
	private final static int STATUS_FAILURE = 1;
	private final static int STATUS_VALIDATE = 2;
	private final static int STATUS_SUCCESS = 3;
	private final static int LOADER_ID_FACE = 1;
	private final static int LOADER_ID_CUSTOMER_INFO = 2;
	//活体检测：值固定为123
	private final int START_LIVE_DETECT = 123;
	protected final static String KEY_INIT_COMPLETED = "init_completed";
	protected final static String KEY_STATUS = "status";

	// 需要存储权限和照相机权限同时授权.
	private static final int PERMISSION_REQUEST_CODE_1 = 1;

	@BindView(R.id.imageView2)
	ImageView mCartoon;
	@BindView(R.id.recognition_succ_hint)
	TextView mSuccessHint;
	@BindView(R.id.recognition_hint_rl1)
	RelativeLayout mHintRl;
	@BindView(R.id.face_recognition_btn)
	Button mNext;
	Unbinder unbinder;
	@BindView(R.id.recognition_hint_rl)
	RelativeLayout mRecognitionHintRl;
	@BindView(R.id.no_network_layout)
	RelativeLayout mNoNetworkLayout;
	@BindView(R.id.apply_quota_steps_desc)
	TextView mStepsDesc;

	//0待刷脸、1刷脸失败、2待验证、3刷脸成功
	private int mStatus = STATUS_WAIT;
	private boolean mInitCompleted;

	private FacePresenter mFacePresenter;
	private CustomerInfoPresenter mCustomerInfoPresenter;
	/**
	 * 初始状态按钮距离顶部控件的高度
	 */
	private int mNormalMarginTop = 118;
	/**
	 * 失败时按钮距离顶部控件的高度
	 */
	private int mFailMarginTop = 86;

	private PermissionsGrantedHelper.PermissionsGrantedListener mGrantedListener = new PermissionsGrantedHelper.PermissionsGrantedListener() {
		@Override
		public void permissionsEachGrantedResult(Permission permission) {
			switch (permission.name) {
				default:
					break;
			}
		}

		@Override
		public void PermissionsAllGrantedResult(boolean granted, int requestCode) {
			switch (requestCode) {
				// 活体检测需要存储和照相机权限同时授权.
				case PERMISSION_REQUEST_CODE_1:
					if (granted) {
						mNext.setEnabled(false);
						startActivityForResult(new Intent(getActivity(), LiveDetectActivity.class), START_LIVE_DETECT);
					} else {
						mNext.setEnabled(true);
						showNeedPermission(getString(R.string.camera_permission_hint, getString(R.string.app_name)));
					}
					break;
				default:
					break;
			}
		}
	};

	public static BaseFragment newInstance(int sectionNumber) {
		BaseFragment fragment = new FaceQuotaFragment();
		Bundle args = new Bundle();
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = getArguments();
		readBundle(bundle);
	}

	@Override
	public void onStart() {
		super.onStart();
		Global.setThirdPartyPageOpenedFlag(false);
	}

	private void readBundle(Bundle savedInstanceState) {
		if (null != savedInstanceState) {
			mInitCompleted = savedInstanceState.getBoolean(KEY_INIT_COMPLETED);
			mStatus = savedInstanceState.getInt(KEY_STATUS);
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putBoolean(KEY_INIT_COMPLETED, mInitCompleted);
		outState.putInt(KEY_STATUS, mStatus);
	}

	@Override
	public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
		super.onViewStateRestored(savedInstanceState);
		readBundle(savedInstanceState);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_FACE:
				return new PresenterLoader<>(getActivity(), new FacePresenter.Generator());
			case LOADER_ID_CUSTOMER_INFO:
				return new PresenterLoader<>(getActivity(), new CustomerInfoPresenter.Generator());
			default:
				return null;
		}
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_FACE:
				CLog.i(TAG, "onLoadFinished() FacePresenter");
				mFacePresenter = (FacePresenter) data;
				mFacePresenter.attach(this);
				break;
			case LOADER_ID_CUSTOMER_INFO:
				CLog.i(TAG, "onLoadFinished() CustomerInfoPresenter");
				mCustomerInfoPresenter = (CustomerInfoPresenter) data;
				mCustomerInfoPresenter.attach(this);
				mCustomerInfoPresenter.getCustomerInfo(Constants.CUSTOMER_TYPE_SFACE);
				break;
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		CLog.i(TAG, "FaceQuotaFragment onResume--");
		//enableNext();
		if (!mInitCompleted) {
			mInitCompleted = true;
		} else {
			CLog.i(TAG, "FaceQuotaFragment onResume() 判断status="+mStatus);
			switch (mStatus) {
				case STATUS_WAIT:
					waitForDetect();
					break;
				case STATUS_FAILURE:
					disableNext();
					break;
				case STATUS_VALIDATE:
					waitForDetect();
					break;
				case STATUS_SUCCESS:
					enableNext();
					break;
			}
		}
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
	}

	@Override
	public void onDetach() {
		super.onDetach();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_my_limit_face_recognition, null);
		mNormalMarginTop = DensityUtil.dip2px(getContext(), 59);
		mFailMarginTop = DensityUtil.dip2px(getContext(), 43);
		unbinder = ButterKnife.bind(this, v);
		return v;
	}

	@OnClick({R.id.face_recognition_btn, R.id.no_network_layout})
	public void onViewClicked(View v) {
		switch (v.getId()) {
			case R.id.face_recognition_btn:
				/*if (STATUS_FAILURE == mStatus) {
					waitForDetect();
				}*/
				switch (mStatus) {
					case STATUS_WAIT:
						String btnText = ((Button)v).getText().toString();
						if(getString(R.string.face_detect).equals(btnText)){
							StatService.onEvent(getContext(), StatIDSet.EVENT_ID_BRUSH_FACE);
						}
					case STATUS_FAILURE:
						mNext.setEnabled(false);
						if (PermissionsGrantedHelper.isSdkUnderM()) {
							// TODO: 2017/6/15 这个判断只在魅族手机上有效?
							if (PermissionsGrantedHelper.checkCameraPermission()) {
								startActivityForResult(new Intent(getActivity(), LiveDetectActivity.class), START_LIVE_DETECT);
							} else {
								mNext.setEnabled(true);
								showNeedPermission(getString(R.string.camera_permission_hint, getString(R.string.app_name)));
							}
						} else {
							PermissionsGrantedHelper.PermissionsAllGranted(mRxPermissions, mGrantedListener, PERMISSION_REQUEST_CODE_1, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
						}
						break;
					case STATUS_SUCCESS:
						((ApplyQuotaActivity) getActivity()).showFragment(ApplyQuotaActivity.PAGE_CREDIT, null);
						break;
				}
				break;
			case R.id.no_network_layout:
				mCustomerInfoPresenter.getCustomerInfo(Constants.CUSTOMER_TYPE_SFACE);
				break;
		}
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		getLoaderManager().initLoader(LOADER_ID_FACE, null, this);
		getLoaderManager().initLoader(LOADER_ID_CUSTOMER_INFO, null, this);
	}

	@Override
	public void onDestroyView() {
		getLoaderManager().destroyLoader(LOADER_ID_FACE);
		getLoaderManager().destroyLoader(LOADER_ID_CUSTOMER_INFO);
		super.onDestroyView();
		unbinder.unbind();
	}
	/**
	 * 显示权限被禁用提示框
	 */
	private void showNeedPermission(String tips){
		showTwoBtnDialog(tips, getString(R.string.go_to_settings), getString(R.string.cancel), new CommonDialog.ButtonClickListener() {
			@Override
			public void onCancel(CommonDialog dialog) {
				dialog.dismiss();
			}

			@Override
			public void onConfirm(CommonDialog dialog) {
				//忽略手势密码
				Global.setThirdPartyPageOpenedFlag(true);
				Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
				startActivity(intent);
				dialog.dismiss();
			}
		}, true);
	}

	private void enableNext() {
		mStatus = STATUS_SUCCESS;
		setBtnMarginTop(mNormalMarginTop);
		mNext.setText(R.string.next_step);
		mCartoon.setImageResource(R.drawable.ic_authority_passed);
		mHintRl.setVisibility(View.GONE);
		mSuccessHint.setText(R.string.face_detect_success);
		mSuccessHint.setVisibility(View.VISIBLE);
	}

	private void disableNext() {
		((ApplyQuotaActivity)getActivity()).setTitle(getString(R.string.save_face_fail));
		mStatus = STATUS_FAILURE;
		setBtnMarginTop(mFailMarginTop);
		mNext.setText(R.string.face_detect_again);
		mCartoon.setImageResource(R.drawable.ic_face_recognition_failed);
		mHintRl.setVisibility(View.VISIBLE);
		mSuccessHint.setText(R.string.face_detect_fail_hint);
		mSuccessHint.setVisibility(View.VISIBLE);
	}

	private void showViews() {
		mCartoon.setVisibility(View.VISIBLE);
		mRecognitionHintRl.setVisibility(View.VISIBLE);
		setBtnMarginTop(mNormalMarginTop);
		mHintRl.setVisibility(View.GONE);
		mSuccessHint.setText(R.string.face_detect_hint);
		mSuccessHint.setVisibility(View.VISIBLE);
		mNext.setVisibility(View.VISIBLE);
	}

	private void waitForDetect() {
		mStatus = STATUS_WAIT;
		setBtnMarginTop(mNormalMarginTop);
		mNext.setText(R.string.face_detect);
		mCartoon.setImageResource(R.drawable.ic_face_recognition_verification);
		mHintRl.setVisibility(View.GONE);
		mSuccessHint.setText(R.string.face_detect_hint);
		mSuccessHint.setVisibility(View.VISIBLE);
		CLog.i(TAG, "waitForDetect()");
	}
	
	private void setBtnMarginTop(int marginTop){
		// 动态设置按钮距离顶部高度
		RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)mNext.getLayoutParams();
		layoutParams.setMargins(0, marginTop, 0, 0);
		mNext.setLayoutParams(layoutParams);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		CLog.i(TAG, " FaceWithdrawFragment requestCode = " + requestCode + " resultCode = " + resultCode);
		if (requestCode == START_LIVE_DETECT) {
			mNext.setEnabled(true);
			switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
				case RESULT_OK:
					if (null != intent) {
						Bundle result = intent.getBundleExtra("result");
						if (null != result) {
							//只有失败时返回  失败动作  l代表静止凝视动作  s代表摇头动作，n代表点头动作
							String mMove = result.getString("mMove");
							//只有失败时返回  失败的原因: 0代表默认失败提示，1代表无人脸，2代表多人脸，3代表活检动作失败，4代表错误动作的攻击，5代表超时，6代表图片加密失败，7代表3D检测失败，8代表肤色检测失败
							String mRezion = result.getString("mRezion");
							//活检是否通过 true代表检测通过，false代表检测失败
							boolean isLivePassed = result.getBoolean("check_pass");
							//图片的byte[]的形式，格式为jpg。失败时返回值为null
							byte[] picByte = result.getByteArray("pic_result");
							if (!TextUtils.isEmpty(mMove)) {
								CLog.i(TAG, "失败动作 mMove = " + mMove);
							}
							if (!TextUtils.isEmpty(mRezion)) {//10为 初始化 失败 ，11为授权过期
								CLog.i(TAG, "失败原因 mRezion = " + mRezion);
							}
							CLog.i(TAG, "检测结果 isLivePassed= " + isLivePassed);
							if (isLivePassed && null != picByte) {//活体检测通过
								showLoading(false);
								mStatus = STATUS_VALIDATE;
								saveFaceInfo(Base64.encodeBase64String(picByte));
							} else {//活体检测失败
								//showToast(R.string.face_detect_fail);
								if(TextUtils.isEmpty(mRezion)){
									mRezion = "unknown";
								}
								onEvent(mRezion);
								disableNext();
							}
						}
					}
					break;
				default:
					break;
			}
		}
	}

	private void saveFaceInfo(String sface) {
		mFacePresenter.saveFaceInfo(sface);
	}

	@Override
	public void saveFaceSuccess() {
		CLog.i(TAG, getString(R.string.save_face_success));
		showToast(R.string.save_face_success1);
		((ApplyQuotaActivity) getActivity()).showFragment(ApplyQuotaActivity.PAGE_CREDIT, null);
	}

	@Override
	public void saveFaceFail(String msg, boolean exit, String retCode) {
		CLog.i(TAG, getString(R.string.face_detect_fail));
		onEvent(retCode);
		disableNext();
		if (exit) {
			showOneBtnDialog(msg, getString(R.string.got_it), new CommonDialog.ButtonClickListener() {
				@Override
				public void onCancel(CommonDialog dialog) {
					dialog.dismiss();
				}

				@Override
				public void onConfirm(CommonDialog dialog) {
					dialog.dismiss();
					getActivity().finish();
				}
			});
		} else {
			showLongToast(msg);
		}
	}

	private void onEvent(String failCode){
		HashMap<String, String> map = new HashMap<>();
		map.put(StatService.ATTRIBUTE_KEY_ONE, failCode);
		StatService.onEvent(getContext(), StatIDSet.EVENT_ID_FACE_DETECT_FAIL, map);
	}

	@Override
	public void customerInfoExist(String type, CustomerBean customerBean) {
		if (Constants.CUSTOMER_TYPE_SFACE.equals(type)) {
			showReloadView(View.GONE);
			showViews();
			enableNext();
		}
	}

	@Override
	public void customerInfoNotExist(String type, String msg) {
		if (Constants.CUSTOMER_TYPE_SFACE.equals(type)) {
			showReloadView(View.GONE);
			showViews();
		}
	}

	@Override
	public void getCustomerInfoError(String type, String msg) {
		if (Constants.CUSTOMER_TYPE_SFACE.equals(type)) {
			showReloadView(View.VISIBLE);
		}
	}

	private void showReloadView(int visible) {
		if ((visible == View.GONE && mNoNetworkLayout.getVisibility() == View.VISIBLE)
				|| (visible == View.VISIBLE && mNoNetworkLayout.getVisibility() == View.GONE)) {
			mNoNetworkLayout.setVisibility(visible);
		}
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips, int functionalCode) {
		super.onFunctionalError(e, autoTips, functionalCode);
		switch (functionalCode) {
			case CustomerInfoModel.METHOD_CUSTOMER_INFO:
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						showReloadView(View.VISIBLE);
					}
				});
				break;
		}
	}
}
